const Web3 = require('web3');
const HDWalletProvider = require("truffle-hdwallet-provider-privkey");
const bip39 = require('bip39');
const util = require('ethereumjs-util');
let tx = require('ethereumjs-tx');
const hdkey = require('ethereumjs-wallet/hdkey');


let web3Util={
    init:(privateKey)=>{

      const provider = new HDWalletProvider([privateKey], "http://154.204.31.226:14441/entaike/eth");


        const web3 = new Web3(provider);
        return web3;
    },
    getRandomWallet:async (size) => {
        let seed = await bip39.mnemonicToSeed(bip39.generateMnemonic());
        let hdWallet = hdkey.fromMasterSeed(seed);
        let walletArr=[]
        for (let i=0;i<size;i++){
            let key = hdWallet.derivePath("m/44'/60'/0'/0/"+i);
            let priKey = util.toChecksumAddress(key._hdkey._privateKey.toString('hex'))
            let pubKey = util.toChecksumAddress(key._hdkey._publicKey.toString('hex'))

            if(priKey.substring(0,2)=='0x')priKey=priKey.substring(2,priKey.length)
            if(pubKey.substring(0,2)=='0x')pubKey=pubKey.substring(2,pubKey.length)
            //将地址byte arr转换为大写16进制
            let address = util.pubToAddress(key._hdkey._publicKey, true);
            address = util.toChecksumAddress(address.toString('hex'));

            walletArr.push({
                priKey:priKey,
                pubKey:pubKey,
                address:address
            })
        }
        return walletArr
    }

}


module.exports=web3Util;
